<template>
  <page-container :title="false" :breadcrumb="false">
    <div class="box-container">
      <a-form-model layout="inline" :model="queryParams">
        <a-form-model-item label="职位名称">
          <a-input v-model="queryParams.positionName" allow-clear />
        </a-form-model-item>
        <a-form-model-item label="职位状态">

          <a-select v-model="queryParams.status" style="width: 160px" allow-clear>
            <a-select-option v-for="item in stateTypeList" :key="item.id" :value="item.dictValue">
              {{ item.dictLabel }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item>
          <a-button
            icon="search"
            html-type="submit"
            @click="getTableDataByFirst"
          >
            查询
          </a-button>
        </a-form-model-item>
      </a-form-model>
    </div>

    <div class="mt10">
      <div class="table_title_operate">
        <div class="left">
          <a-button
            type="primary"
            plain
            @click="onOpenAddPostModal"
          >新增职位</a-button>
        </div>
        <div class="right">
          <a-button
            type="danger"
            @click="onDeletePosts"
          >批量删除</a-button>

          <a-button
            class="ml10"
            type="warning"
            @click="onExport"
          >导出</a-button>
        </div>
      </div>

      <s-table
        ref="table"
        class="bg-white"
        row-key="id"
        :columns="tableParams.columns"
        :data="tableParams.loadData"
        :row-selection="{ selectedRowKeys: tableParams.rowSelection.selectedRowKeys, onChange: tableParams.rowSelection.onChange }"
        :init-request="tableParams.initRequest"
        :pagination="tableParams.pagination"
      >
        <span slot="status" slot-scope="text">
          <a-badge v-if="text === 'ENABLE'" status="success" text="启用" />
          <a-badge v-else status="error" text="停用" />
        </span>
        <span slot="remark" slot-scope="text">
          <text-tooltip :content="text" />
        </span>
        <span slot="operate" slot-scope="text, record, index">
          <template>
            <a @click="onOpenModifyPostModal(index, record)">修改</a>
            <a-divider type="vertical" />
            <a @click="onDeletePost(index, record)">删除</a>
          </template>
        </span>
      </s-table>
    </div>

    <a-modal v-model="open" :title="title">
      <a-form-model ref="postForm" :model="postForm" :rules="postFormRules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item prop="positionName" label="职位名称">
          <a-input v-model="postForm.positionName" />
        </a-form-item>
        <a-form-item label="职位状态">
          <a-radio-group v-model="postForm.status">
            <a-radio v-for="item in stateTypeList" :key="item.id" :value="item.dictValue">{{ item.dictLabel }}</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="备注">
          <a-input v-model="postForm.remark" type="textarea" :rows="3" />
        </a-form-item>

      </a-form-model>

      <template slot="footer">
        <a-button key="back" @click="open = false">
          取消
        </a-button>

        <template v-if="!postForm.id">
          <!--新增-->
          <a-button key="submit" type="primary" @click="onAddOrModifyPost">确认</a-button>
        </template>
        <template v-else>
          <!--修改-->
          <a-button key="submit" type="primary" @click="onAddOrModifyPost">确认</a-button>
        </template>

      </template>
    </a-modal>
  </page-container>
</template>

<script>
import { parseTime } from '@/utils'
import { addPostApi, modifyPostApi, getPostListApi, deletePostApi, deletePostsApi, exportPostApi } from '@/api/system/post'
import { debounce } from '@/utils'

export default {
  name: 'Post',
  data() {
    const columns = [
      {
        title: '职位名称',
        dataIndex: 'positionName'
      },
      {
        title: '职位状态',
        dataIndex: 'status',
        scopedSlots: { customRender: 'status' }
      },
      {
        title: '创建时间',
        dataIndex: 'createDate',
        customRender(createDate) {
          return parseTime(createDate)
        }
      },
      {
        title: '备注',
        dataIndex: 'remark',
        width: '150px',
        scopedSlots: { customRender: 'remark' }
      },
      {
        title: '操作',
        dataIndex: 'operate',
        scopedSlots: { customRender: 'operate' }
      }
    ]

    return {
      stateTypeList: [],
      queryParams: {
        positionName: undefined,
        status: undefined
      },

      tableParams: {
        pagination: {
          showTotal: total => `共 ${total} 条`,
          showQuickJumper: true,
          pageSizeOptions: ['5', '10', '15', '20']
        },
        columns,
        loadData: parameter => {
          const requestParameters = Object.assign({}, parameter, this.$parseQueryParams(this.queryParams))
          return getPostListApi(requestParameters)
            .then(res => {
              return res.data
            })
        },
        rowSelection: {
          selectedRowKeys: [],
          onChange: this.onSelectChange
        },
        selectedRowKeys: [],
        selectedRows: [],
        initRequest: true
      },

      title: '',
      open: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      postForm: {},
      postFormRules: {
        positionName: [
          { required: true, message: '职位名称不能为空', trigger: 'blur' }
        ]
      },
      loading: false
    }
  },
  created() {
    this.initDict()
    this.getTableDataByFirst()
  },
  methods: {
    getTableDataByFirst() {
      this.$refs.table && this.$refs.table.refresh(true)
    },

    /**
     * 初始化数据字典
     */
    initDict() {
      this.$getCodeDictMap(this, {
        STATUS_TYPE: 'stateTypeList'
      })
    },

    /**
     * 重置职位添加或修改表单
     */
    resetPostForm() {
      this.postForm = {
        id: undefined,
        positionName: undefined,
        status: 'ENABLE',
        remark: undefined
      }
      // this.$resetForm('postForm')
    },

    /**
     * 打开新增表单弹窗
     */
    onOpenAddPostModal() {
      this.resetPostForm()
      this.title = '新增职位'
      this.open = true
    },

    /**
     * 打开修改表单弹窗
     * @param index 当前职位数组索引
     * @param post 当前职位信息
     */
    onOpenModifyPostModal(index, post) {
      this.resetPostForm()
      this.postForm = { ...post }
      this.title = '修改职位'
      this.open = true
    },

    /**
     * 新增或修改职位信息
     */
    onAddOrModifyPost: debounce(function() {
      this.$refs.postForm.validate((valid) => {
        if (valid) {
          if (this.postForm.id === undefined) { // 新增职位
            addPostApi(this.postForm).then((res) => {
              if (res.code === 'A00000') {
                this.$message.success(res.msg)
                this.open = false
                this.getTableDataByFirst()
              } else {
                this.$message.error(res.msg)
              }
            })
          } else { // 修改职位
            modifyPostApi(this.postForm).then((res) => {
              if (res.code === 'A00000') {
                this.$message.success(res.msg)
                this.open = false
                this.getTableDataByFirst()
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        }
      })
    }),

    /**
     * 删除职位
     */
    onDeletePost(index, post) {
      this.$confirm({
        title: '提示',
        content: '确认删除当前职位, 是否继续?',
        okText: '确定',
        cancelText: '取消',
        type: 'warning',
        onOk: () => {
          deletePostApi(post).then((res) => {
            if (res && res.code === 'A00000') {
              this.getTableDataByFirst()
              this.$message.success(res.msg)
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },

    /**
     * 批量删除
     */
    onDeletePosts() {
      const postIds = this.tableParams.rowSelection.selectedRowKeys
      if (postIds.length === 0) {
        this.$message.warning('请选择职位')
        return
      }

      this.$confirm({

        title: '提示',
        content: '确认批量删除, 是否继续?',
        okText: '确定',
        cancelText: '取消',
        type: 'warning',
        onOk: () => {
          deletePostsApi(postIds).then((res) => {
            if (res && res.code === 'A00000') {
              this.$message.success(res.msg)
              this.getTableDataByFirst()
            }
          })
        }
      })
    },

    /**
     * 导出用户
     */
    onExport: debounce(function() {
      const postIds = this.tableParams.rowSelection.selectedRowKeys
      if (postIds.length === 0) {
        this.$message.warning('请选择职位')
        return
      }

      exportPostApi(postIds).then((res) => {
        if (res) {
          this.$exportFile('职位.xls', [res])

          this.$refs.table.clearSelected()
        }
      })
    }),

    /**
     * 表格多选示例
     * @param selectedRowKeys
     * @param selectedRows
     */
    onSelectChange(selectedRowKeys, selectedRows) {
      this.tableParams.rowSelection.selectedRowKeys = selectedRowKeys

      // this.tableParams.selectedRowKeys = selectedRowKeys
      // this.tableParams.selectedRows = selectedRows
    }
  }
}
</script>

<style scoped>
/** 全局表格头部操作 */
.table_title_operate{
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

</style>
